﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Diagnostics;

namespace Eniux.Framework.Infrastructure
{
    /// <summary>
    /// ViewModel基类
    /// </summary>
     public abstract  class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        #region INotifyPropertyChanged

         public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        ///更改属性值
        /// </summary>
        public bool NotifyPropertyChanged<T>(ref T field, T value, Expression<Func<T>> property)
        {
            if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                field = value;
                NotifyPropertyChanged(property);
                return true;
            }
            return false;
        }

        private void NotifyPropertyChanged<T>(Expression<Func<T>> property)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                var memberExpression = (property.Body is UnaryExpression)
                                        ? ((UnaryExpression)property.Body).Operand as MemberExpression
                                        : property.Body as MemberExpression;
                Debug.Assert(memberExpression != null);
                handler(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
            }
        }

        /// <summary>
        /// 通过属性名称更改属性值
        /// </summary>
        protected void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region IDisposable 

         /// <summary>
         /// 释放对象
        /// </summary>
        public void Dispose()
        {
            this.OnDispose();
        }

        protected virtual void OnDispose()
        {
        }

#if DEBUG
        /// <summary>
        /// 调试提示信息，确保对象被GC回收
        /// </summary>
        ~ViewModelBase()
        {
            string msg = string.Format("{0} ({2}) Finalized",
                this.GetType().Name,this.GetHashCode());
            System.Diagnostics.Debug.WriteLine(msg);
        }
#endif

        #endregion 

    }
}
